﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace hmt_html
{
    class htmtohtml
    {
        public void readAndCreateMultFile(string inputfilepath, string outputfilepath)
        {
            bool isCreateHtml = false;
            bool isTableContent = false;
            bool isGetResName = false;
            string resName = null;
            StringBuilder resSb = new StringBuilder();

            int trLine = 1;
            int htmlNo = 1;

            string htmlFileName = System.IO.Path.GetFileNameWithoutExtension(inputfilepath);

            bool isCreateHtmlOK = false;

            string line = String.Empty;
            StringBuilder sb = null;
            var reader = new StreamReader(inputfilepath, Encoding.UTF8);
            while ((line = reader.ReadLine()) != null)
            {
                //解析文字信息
                if (!isCreateHtml)
                {
                    Match startMatch = tableStartPattern().Match(line);
                    if (startMatch.Success && !isCreateHtmlOK)
                    {
                        isTableContent = true;// 找到 table
                                              //将table 后面的 tr 内容拼接起来
                        sb = (new StringBuilder(startMatch.Groups[2].Value)).Append("\r\n");
                        isCreateHtmlOK = true;
                    }
                    else
                    {
                        if (isTableContent)
                        {
                            trLine++;
                            string patternend = "(.*?)(</table>).*(/tr)";
                            Match endMatch = tableEndPattern().Match(line);
                            if (endMatch.Success)
                            {
                                string aabv = "";
                            }
                            if (!new Regex(patternend).Match(line).Success && endMatch.Success)
                            {
                                sb.Append(endMatch.Groups[1].Value.Trim());
                                createHtmlFile(outputfilepath, htmlFileName, sb.ToString(), htmlNo, true);
                                isCreateHtml = true;
                            }
                            else
                            {
                                sb.Append(line).Append("\r\n");
                                if (trLine % 1000 == 0)
                                {
                                    createHtmlFile(outputfilepath, htmlFileName, sb.ToString(), htmlNo, false);
                                    htmlNo++;
                                    sb.Remove(0, sb.Length);
                                }
                            }
                        }

                    }
                }

                //解析资源信息 图片 CSS 等

                if (isCreateHtml)
                {
                    if (!isGetResName)
                    {
                        Match resMatch = resourceNamePattern().Match(line);
                        if (resMatch.Success)
                        {
                            resName = resMatch.Groups[1].Value;
                            isGetResName = true;
                            resSb.Remove(0, resSb.Length);
                            continue;
                        }

                    }
                }
                if (isGetResName)
                {
                    if (line.Length > 0)
                    {
                        if (line.Contains("------=_NextPart_"))
                        {
                            isGetResName = false;
                            generateImage(resSb.ToString(), (outputfilepath + "\\" + htmlFileName), resName);
                        }
                        else
                        {
                            resSb.Append(line).Append("\r\n");
                        }
                    }
                }
            }

        }
        private static bool isHtmlStartTag(string content)
        {
            string pattern = ".*<html .*>.*";
            return new Regex(pattern).IsMatch(content);
        }
        private static bool isHtmlEndTag(string content)
        {
            return content.Contains("</html>");
        }
        private static Regex tableStartPattern()
        {
            string pattern = "(<table .*?>)(.*)";
            return new Regex(pattern);
        }
        private static Regex tableEndPattern()
        {
            string pattern = "(.*?)(</table>)";
            return new Regex(pattern);
        }
        private static Regex resourceNamePattern()
        {
            string pattern = "Content-Location:(.*)";
            return new Regex(pattern);
        }

        /// <summary>
        /// 创建html文件 </summary>
        /// <param name="outputFilePath"> </param>
        /// <param name="htmlFileName"> </param>
        /// <param name="htmlContent"> </param>
        public static void createHtmlFile(string outputFilePath, string htmlFileName, string htmlContent, int htmlNo, bool isEndCreate)
        {
            try
            {
                string folderName = htmlFileName;
                //outputFilePath = outputFilePath.EndsWith("\\", StringComparison.Ordinal) ? outputFilePath : outputFilePath + File.separator;

                if (!Directory.Exists(outputFilePath + "\\" + htmlFileName))
                {
                    Directory.CreateDirectory(outputFilePath + "\\" + htmlFileName);
                }
                var filepath = outputFilePath + "\\" + htmlFileName + "\\" + htmlFileName + "-" + htmlNo + ".html";
                if (!File.Exists(filepath))
                {
                    FileStream fs = new FileStream(filepath, FileMode.Create, FileAccess.ReadWrite);
                    StreamWriter sw = new StreamWriter(fs);
                    if (htmlNo == 0)
                    {
                        sw.Write(htmlContent);
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder("<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />" + "<title>QQ Message</title><style type=\"text/css\">body{font-size:12px; line-height:22px; margin:2px;}td{font-size:12px; line-height:22px;}</style></head><body>");
                        sb.Append("<table width=100% cellspacing=0>");
                        if (!isEndCreate)
                        {
                            sb.Append("<tr>");
                            if (htmlNo == 1)
                            {
                                sb.Append("<td>");
                            }
                            else
                            {
                                sb.Append("<td style=\"height:40px;\">");
                            }
                            if (htmlNo > 1)
                            {
                                sb.Append("<a href=\"").Append(htmlFileName).Append("-").Append(htmlNo - 1).Append(".html\">上一页</a>").Append("&nbsp;&nbsp;&nbsp;");
                            }
                            sb.Append("<a href=\"").Append(htmlFileName).Append("-").Append(htmlNo + 1).Append(".html\">下一页</a>");
                            sb.Append("</td><tr>");
                        }
                        else
                        {
                            if (htmlNo > 1)
                            {
                                sb.Append("<tr><td style=\"height:40px;\"><a href=\"").Append(htmlFileName).Append("-").Append(htmlNo - 1).Append(".html\">上一页</a></td><tr>");
                            }
                        }
                        sb.Append(htmlContent).Append("</table></body></html>");
                        sw.Write(sb.ToString());
                    }
                    sw.Flush();
                    sw.Close();
                }
            }
            catch (IOException e)
            {
                Console.WriteLine(e.ToString());
                Console.Write(e.StackTrace);
            }
        }


        /// <summary>
        /// 对字节数组字符串进行Base64解码并生成图片 </summary>
        /// <param name="imgStr"> 图片数据 </param>
        /// <param name="imgFilePath"> 保存图片全路径地址 </param>
        /// <param name="filename"> 保存的附件名称
        /// @return </param>
        public static string generateImage(string imgStr, string imgFilePath, string filename)
        {
            if (imgStr.Length <= 0)
            {
                return null;
            }
            /// <summary>
            /// 判断保存图片的路径是否存在，如果不存在则创建此路径中。
            /// </summary>
            /// 

            if (!File.Exists(imgFilePath))
            {
                FileStream fs = new FileStream(imgFilePath + "\\" + filename, FileMode.Create, FileAccess.ReadWrite);
                BinaryWriter sw = new BinaryWriter(fs);

                byte[] decodedByteArray = Convert.FromBase64String(imgStr);
                sw.Write(decodedByteArray, 0, decodedByteArray.Length);
                sw.Flush();
                sw.Close();


            }

            return filename;
        }
    }
}
